<?php
/**
 * CoinLog.class.php
 *
 * @author camfee <camfee@foxmail.com>
 * @date   18-1-15 下午1:17
 */

namespace Center;

use Common\ModuleBase;
use Common\Bridge;

class CoinLog extends ModuleBase
{
    protected static $_conf = [
        'db' => [
            'w' => Bridge::DB_CENTER_W,
            'r' => Bridge::DB_CENTER_R
        ],
        'table' => 'CoinLog',
        'fields' => [
            'CoinLogId' => self::VAR_TYPE_KEY,
            'UserId' => self::VAR_TYPE_INT,
            'Type' => self::VAR_TYPE_INT,
            'CoinNum' => self::VAR_TYPE_INT,
            'Status' => self::VAR_TYPE_INT,
            'Info' => self::VAR_TYPE_STRING,
            'UpdateTime' => self::VAR_TYPE_STRING,
            'CreateTime' => self::VAR_TYPE_STRING,
            'AppId' => self::VAR_TYPE_INT,
        ],
        'mc' => Bridge::MEMCACHE_DEFAULT,
        // 可选, MC KEY, "KeyName:%d", %d会用主键ID替代
        'mckey' => 'CoinLog:%d',
        // 可选, 超时时间, 默认不过期
        'mctime' => 86400,
    ];

    // 1:参加活动 2:投票 100：充值 101：邀请 102：注册 103：商家赠送 104：其他 105:商家扫码 106:首次支付 107 充值赠送
    const TYPE_ACTIVE = 1;
    const TYPE_VOTE = 2;
    const TYPE_EXCHANGE = 100;
    const TYPE_INVITE = 101;
    const TYPE_REG = 102;
    const TYPE_DONATE = 103;
    const TYPE_OTHER = 104;
    const TYPE_SCAN_QRCODE = 105;
    const TYPE_FIRST_PAY = 106;
    const TYPE_PAY_DONATE = 107;

    const TYPE_LIST = [
        self::TYPE_ACTIVE => '参加活动',
        self::TYPE_VOTE => '投票',
        self::TYPE_EXCHANGE => '充值',
        self::TYPE_INVITE => '邀请',
        self::TYPE_REG => '注册',
        self::TYPE_DONATE => '商家赠送',
        self::TYPE_OTHER => '其他',
        self::TYPE_SCAN_QRCODE => '商家扫码',
        self::TYPE_FIRST_PAY => '首次充值',
        self::TYPE_PAY_DONATE => '充值赠送',
    ];

    const MC_LIST_COIN_LOG = 'LIST_COIN_LOG:{UserId}';
    protected static $_cache_list_keys = [
        self::MC_LIST_COIN_LOG => [
            self::CACHE_LIST_TYPE => self::CACHE_LIST_TYPE_MC,
            self::CACHE_LIST_FIELDS => 'UserId',
        ],
    ];

    const MC_RANK_MONTH = 'Coin_Rank_Month';
    const MC_RANK_QUARTER = 'Coin_Rank_Quarter';
    const MC_RANK_YEAR = 'Coin_Rank_Quarter';

    /**
     * @param int $type 1:当月 2：当季 3：当年
     * @param int $limit
     * @return array
     */
    public static function getRankList($type, $limit = 100)
    {
        if ($type == 1) {
            $start_time = date('Y-m-01 00:00:00');
        } elseif ($type == 2) {
            switch ((int)date('m')) {
                case 1:
                case 2:
                    $start_time = date('Y-12-01 00:00:00', strtotime('-1 years'));
                    break;
                case 3:
                case 4:
                case 5:
                    $start_time = date('Y-03-01 00:00:00');
                    break;
                case 6:
                case 7:
                case 8:
                    $start_time = date('Y-06-01 00:00:00');
                    break;
                case 9:
                case 10:
                case 11:
                    $start_time = date('Y-09-01 00:00:00');
                    break;
                case 12:
                    $start_time = date('Y-12-01 00:00:00');
                    break;
                default:
                    $start_time = '';
            }
        } elseif ($type == 3) {
            $start_time = date('Y-01-01 00:00:00');
        } else {
            $start_time = '';
        }
        $where = "WHERE Type = " . self::TYPE_SCAN_QRCODE . " AND CreateTime >= '{$start_time}'";

        $sql = 'SELECT UserId,SUM(CoinNum) as Num FROM CoinLog ' . $where . ' GROUP BY UserId ORDER BY Num DESC limit ' . $limit;
        $query = self::getPdo()->prepare($sql);
        $query->execute();
        $list = $query->fetchAll();
        $data = $uids = [];
        if (!empty($list)) {
            foreach ($list as $v) {
                $uids[] = $v['UserId'];
            }
            $users = User::getInfoByIds($uids);
            $i = 1;
            foreach ($list as $v) {
                $uid = $v['UserId'];
                if (isset($users[$uid])) {
                    $data[] = [
                        'Rank' => $i,
                        'JCoinNum' => $v['Num'],
                        'UserId' => $uid,
                        'UserNick' => $users[$uid]['UserNick'],
                        'HeadUrl' => $users[$uid]['HeadUrl']
                    ];
                    $i++;
                }
            }
        }

        return $data;
    }

    /**
     * 增加金币记录
     *
     * @param      $uid
     * @param      $coin
     * @param int  $type
     * @param bool $auto_update 自动更改用户金币数
     * @return bool|int|string
     */
    public static function addCoinLog($uid, $coin, $type = self::TYPE_EXCHANGE, $auto_update = true, $info = '')
    {
        $add = [
            'UserId' => $uid,
            'CoinNum' => abs($coin),
            'Type' => $type,
            'AppId' => $GLOBALS['g_appid'] ?? 50,
            'CreateTime' => date('Y-m-d H:i:s')
        ];
        if ($info != '') {
            $add['Info'] = $info;
        }
        if ($auto_update) {
            if ($type >= 100) {
                $seek = '+';
            } else {
                $seek = '-';
            }
            User::update($uid, ['JCoin' => ['JCoin', $seek . abs($coin)]]);
        }

        return self::add($add);
    }

    /**
     * 获取Id列表
     *
     * @param     $uid
     * @param int $offset
     * @param int $limit
     * @return array
     */
    public static function getUserList($uid, $offset = 0, $limit = 10)
    {
        $where = [
            'UserId' => $uid,
        ];
        $extra = [
            'type' => parent::MOD_TYPE_MEMCACHE,
            'mckey' => self::MC_LIST_COIN_LOG,
            'mtime' => 86400,
            'order' => '',
        ];
        $data = parent::getDataByFields($where, $extra);

        if (!empty($data['data'])) {
            $data['data'] = array_slice($data['data'], $offset, $limit);
        }

        return $data;
    }

    /**
     * @see ModuleBase::add() 新增
     * @see ModuleBase::update() 更新
     * @see ModuleBase::getInfoByIds() 按id查询
     * @see ModuleBase::getList() 条件查询
     * @see ModuleBase::delete() 删除
     */

}